package cn.cloudtogo.server.module.datasource;

import cn.cloudtogo.common.DatasourceQueryService;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import cn.cloudtogo.common.types.Pair;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yaolianhua789@gmail.com
 **/
@Service
@Slf4j
public class ExternalDatasourceQueryService implements DatasourceQueryService {

    private final ExternalDatasourceDao datasourceDao;

    public ExternalDatasourceQueryService(ExternalDatasourceDao datasourceDao) {
        this.datasourceDao = datasourceDao;
    }

    @Override
    public List<Pair> list(String openid) {
        List<ExternalDatasourceModel> datasources = datasourceDao.list(openid);
        List<Pair> pairs = datasources.stream()
                .map(model -> {
                    Map<String, Object> map = Map.of("datasourceId", model.getUuid(),
                            "component", model.getName(),
                            "middlewareId", model.getOpenid(),
                            "schema", model.getSchema(),
                            "host", model.getHost(),
                            "port", model.getPort(),
                            "user", model.getUsername(),
                            "password", model.getPassword(),
                            "type", model.getType());
                    return Pair.pair(map);
                }).collect(Collectors.toList());
        return pairs;
    }

    @Override
    public Pair query(String uuid) {
        ExternalDatasourceModel model = datasourceDao.query(uuid);
        if (null == model) {
            return null;
        }
        Map<String, Object> map = Map.of("datasourceId", uuid,
                "component", model.getName(),
                "middlewareId", model.getOpenid(),
                "schema", model.getSchema(),
                "host", model.getHost(),
                "port", model.getPort(),
                "user", model.getUsername(),
                "password", model.getPassword(),
                "type", model.getType());

        return Pair.pair(map);

    }
}
